package sunsun.xiaoli.jiarebang.device;

import android.Manifest;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.itboye.pondteam.base.BaseActivity;
import com.itboye.pondteam.bean.PersonDataBean;
import com.itboye.pondteam.interfaces.PermissionListener;
import com.itboye.pondteam.presenter.UserPresenter;
import com.itboye.pondteam.utils.Const;
import com.itboye.pondteam.utils.SPUtils;
import com.itboye.pondteam.utils.loadingutil.MAlert;
import com.itboye.pondteam.utils.udp.VersionUtil;
import com.itboye.pondteam.volley.ResultEntity;
import org.jetbrains.annotations.NotNull;
import sunsun.xiaoli.jiarebang.BuildConfig;
import sunsun.xiaoli.jiarebang.R;
import sunsun.xiaoli.jiarebang.app.App;
import sunsun.xiaoli.jiarebang.custom.ClearEditText;
import sunsun.xiaoli.jiarebang.device.pondteam.ChooseLanguageActivity;
import sunsun.xiaoli.jiarebang.device.pondteam.PondTeamRegisterActivity;
import sunsun.xiaoli.jiarebang.logincontroller.LoginController;
import sunsun.xiaoli.jiarebang.logincontroller.LoginedState;
import sunsun.xiaoli.jiarebang.utils.AreaCodeSelectHelper;
import sunsun.xiaoli.jiarebang.utils.IAreaCodeSelect;
import sunsun.xiaoli.jiarebang.utils.SpContants;

import java.util.List;
import java.util.Observable;
import java.util.Observer;


/**
 * Created by itboye on 2017/2/24.
 */

public class LoginActivity extends BaseActivity implements Observer, IAreaCodeSelect {
    private TextView btn_login, btn_register;//denglu
    String email, password;
    ClearEditText editextUsetName, editextPassword;
    String userName = "";
    String userPass = "";
    UserPresenter userPresenter;
    TextView txt_forget_pass, title_login, btn_country, tv_language_choose;
    TextView bottom_icon;
    String country = "+86";
    IAreaCodeSelect iAreaCodeSelect;
    TextView txt_version;
    Button btn_wechat, btn_qq, btn_weibo;
    RelativeLayout re_third_login;
    App mApp;

    public static LoginActivity loginActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        loginActivity = this;
        userPresenter = new UserPresenter(this);
        if (BuildConfig.APP_TYPE.equalsIgnoreCase("pondteam")) {
            PERMISSIONS_STORAGE = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
        }
        mApp = (App) getApplication();
//        listener = new BaseUiListener();
        String appType = BuildConfig.APP_TYPE;
        Drawable top = getResources().getDrawable(R.drawable.pondlink_icon);// 获取res下的图片drawable
        top.setBounds(0, 0, 250, 250);// 一定要设置setBounds();
        if (appType.toLowerCase().contains("pondteam".toLowerCase())) {
            title_login.setText("PondLink By Pondteam");
            bottom_icon.setVisibility(View.INVISIBLE);
            btn_country.setVisibility(View.INVISIBLE);
            tv_language_choose.setVisibility(View.VISIBLE);
            editextUsetName.setHint(getString(R.string.email));
            userPresenter.setBaseUrl(Const.pondlink_wrapUrl);
            txt_version.setCompoundDrawables(null, top, null, null);
        } else {
            title_login.setText(getString(R.string.login_sunsun));
            btn_country.setVisibility(View.VISIBLE);
            editextUsetName.setHint(getString(R.string.user_name));
            bottom_icon.setVisibility(View.INVISIBLE);
        }
        if (getPackageName().contains("pondlink")) {
            title_login.setText("PondLink By Pondteam");
            bottom_icon.setVisibility(View.INVISIBLE);
            bottom_icon.setBackgroundColor(getResources().getColor(R.color.login_color));
            bottom_icon.setText("pondLink");
            txt_version.setCompoundDrawables(null, top, null, null);
            bottom_icon.setTextSize(20);
        } else if (getPackageName().contains("xiaomianyang")) {
            title_login.setText(getString(R.string.login_yihu));
            btn_country.setVisibility(View.VISIBLE);
            editextUsetName.setHint(getString(R.string.user_name));
            bottom_icon.setVisibility(View.INVISIBLE);
        }

        if (SpContants.APP_TYPE.equals("水族之家")) {
            title_login.setText(getString(R.string.app_lingshou_name));
            re_third_login.setVisibility(View.GONE);
        }
        txt_version.setText(getString(R.string.current_version) + VersionUtil.getVersionName());
    }

    private static String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA};

    @Override
    public void onClick(View view) {
        userName = editextUsetName.getText().toString().trim();
        userPass = editextPassword.getText().toString().trim(); Intent intent =null;

        switch (view.getId()) {
            case R.id.btn_register:
                intent = new Intent(LoginActivity.this, PondTeamRegisterActivity.class);
                startActivity(intent);
//                onUIAlertView(view);
                break;
            case R.id.btn_login:
//                if (userName.equals("") || userName.equals("")) {
//                    MAlert.alert(getString(R.string.username_empty));
//                    return;
//                }
                if (Build.VERSION.SDK_INT >= 23) {//判断当前系统是不是Android6.0
                    requestRuntimePermissions(PERMISSIONS_STORAGE, new PermissionListener() {
                        @Override
                        public void granted() {
                            //权限申请通过
                            mobileLogin();
                        }

                        @Override
                        public void denied(List<String> deniedList) {
                            if (deniedList != null && deniedList.size() > 0) {
                                openAppDetails(getString(R.string.need_access));
                            }
//                            //权限申请未通过
//                            for (String denied : deniedList) {
//                                if (denied.equals(PERMISSIONS_STORAGE[0])) {
//                                    break;
//                                } else {
//
//                                }
//                            }
                        }
                    });
                } else {
                    mobileLogin();
                }
                break;
            case R.id.txt_forget_pass:
                intent = new Intent(LoginActivity.this, ForgetPasswordActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_country:
                new AreaCodeSelectHelper().showAreaCode(this, R.layout.item_choose_code, btn_country, this);
                break;
//            case R.id.btn_wechat:
//                weChatLogin();
//                break;
//            case R.id.btn_qq:
//                tencentQQLogin();
//                break;
//            case R.id.btn_weibo:
//                weiboLogin();
//                break;
            case R.id.tv_language_choose:
                //选择语言
                startActivity(new Intent(this, ChooseLanguageActivity.class));
                break;
        }
    }

    private void mobileLogin() {
        if (isEmpty(userName) || isEmpty(userPass)) {
            MAlert.alert(getResources().getString(R.string.phone_or_psw_empty));
            return;
        }
        System.out.println("登录-----------");
        showProgressDialog(getString(R.string.requesting), true);
        userPresenter.login(country, userName, userPass, "");
    }

    private void weiboLogin() {

    }

    private void tencentQQLogin() {
//        if (!mApp.getmTencent().isSessionValid()) {
//            mApp.getmTencent().login(this, "", listener);
//        }
    }

    private void weChatLogin() {
//        SendAuth.Req req = new SendAuth.Req();
//        req.scope = "snsapi_userinfo";
//        req.state = "wechat_sdk_demo_test";
//        mApp.getIwxapi().sendReq(req);
    }

//    private class BaseUiListener implements IUiListener {
//        protected void doComplete(Object values) {
//            MAlert.alert(values);
//        }
//
//        @Override
//        public void onComplete(Object o) {
//            doComplete(o);
//        }
//
//        @Override
//        public void onError(UiError e) {
//        }
//
//        @Override
//        public void onCancel() {
//        }
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        Tencent.onActivityResultData(requestCode, resultCode, data, listener);
    }

    @Override
    public void update(Observable o, Object data) {
        ResultEntity resultEntity = handlerError(data);
        try {
            closeProgressDialog();
        } catch (Exception e) {

        }
        if (resultEntity != null) {
            if (resultEntity.getCode() != 0) {
                MAlert.alert(resultEntity.getMsg());
                return;
            }
            if (resultEntity.getEventType() == UserPresenter.login_success) {
                PersonDataBean personDataBean = (PersonDataBean) resultEntity.getData();
                if (personDataBean != null) {
                    setMyData(personDataBean);
                    MAlert.alert(getString(R.string.login_success));
                    Intent intent = new Intent(this, DeviceActivity.class);
                    startActivity(intent);
                    finish();
                }
            } else if (resultEntity.getEventType() == UserPresenter.login_fail) {
                MAlert.alert(resultEntity.getData());
            }

        }
    }

    public void setMyData(PersonDataBean bean) {
        SPUtils.put(LoginActivity.this, null,
                Const.UID, bean.getId());
        SPUtils.put(LoginActivity.this, null,
                Const.PaySecret, bean.getPaySecret());
        SPUtils.put(LoginActivity.this, null,
                Const.RELE, "6");
        if (bean.getIs_stores() != null) {
            SPUtils.put(LoginActivity.this, null,
                    Const.IS_STORE, bean.getIs_stores());
        }
        SPUtils.put(LoginActivity.this, null,
                Const.EMAIL, bean.getEmail());
        SPUtils.put(LoginActivity.this, null,
                Const.USERNAME, bean.getUsername());
        SPUtils.put(LoginActivity.this, null,
                Const.PASSWORD, bean.getPassword());
        SPUtils.put(LoginActivity.this, null,
                Const.MOBILE, bean.getMobile());
        SPUtils.put(LoginActivity.this, null,
                Const.IS_LOGINED, true);
        SPUtils.put(LoginActivity.this, null,
                Const.HEAD, bean.getHead());
        SPUtils.put(LoginActivity.this, null,
                Const.NICK, bean.getNickname());
        SPUtils.put(LoginActivity.this, null,
                Const.USER_DEVICE_NUMBER, bean.getUser_device_number() + "");
        SPUtils.put(LoginActivity.this, null,
                Const.INVITE_CODE, bean.getIdcode() + "");

//        SPUtils.put(LoginActivity.this, null,
//                Const.ISAUTH, bean.getRolesInfo().get(0).getIsAuth());
        SPUtils.put(LoginActivity.this, null,
                Const.S_ID, bean.getAutoLoginCode());
        if (bean.get_gm() == 0) {
            SPUtils.put(LoginActivity.this, null,
                    Const.GM, "user");
        } else {
            SPUtils.put(LoginActivity.this, null,
                    Const.GM, "gm");
        }
        LoginController.setLoginState(new LoginedState());
    }

    @Override
    public void selectFinish(@NotNull String code) {
        country = code;
    }
}
